/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Student;

import Address.AddressBean;
import User.UserBean;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.sql.Date;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

/**
 *
 * @author mishra
 */
public class EditStudent extends HttpServlet {

    /**
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
     * methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    long j = 0;
    HashMap htmlfields = new HashMap();
    File fi = null;
    StudentBean sb = new StudentBean();
    AddressBean adb = new AddressBean();
    int i = 0;

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException, ParseException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        HttpSession session = request.getSession();
        Date dob = null;
        boolean isMultipart = ServletFileUpload.isMultipartContent(request);
        if (isMultipart) {
            try {
                ServletFileUpload servlet = new ServletFileUpload();
                FileItemIterator fit = servlet.getItemIterator(request);
                while (fit.hasNext()) {
                    FileItemStream f = fit.next();
                    if (f.isFormField()) {
                        InputStream input = f.openStream();
                        byte b[] = new byte[input.available()];
                        input.read(b);
                        String value = new String(b);
                        htmlfields.put(f.getFieldName(), value);
                    } else {
                        if (f.getName().isEmpty()) {
                            continue;
                        } else {
                            String fileName = (String) htmlfields.get("admissionId");
                            String postfix = "@photo";

                            String s = DocUpload.FileUpload.writeFile(f, fileName + postfix);
                            sb.setPhotoName(s);
                        }
                    }
                }
            } catch (Exception e) {
            }
        }

        try {
            int stuChk = Student.Query.chkStudent(sb.getAdmissionId(), sb.getStudentId());

            adb.setAddress1(htmlfields.get("stuAdd1").toString());
            adb.setAddress2(htmlfields.get("stuAdd2").toString());
            if (htmlfields.get("country").toString().length() != 0) {
                adb.setCountryId(Integer.parseInt(htmlfields.get("country").toString()));
            }

            if (htmlfields.get("state").toString().length() != 0) {
                adb.setStateId(Integer.parseInt(htmlfields.get("state").toString()));
            }
            adb.setPinCode(htmlfields.get("pin").toString());
            if (htmlfields.get("addrid").toString().length() != 0) {
                adb.setAddressId(Integer.parseInt(htmlfields.get("addrid").toString()));
            }
            if (stuChk != 0) {
                Address.Query.edit(adb);
            } else {
                int k = Address.Query.add(adb);
                adb.setAddressId(k);

            }
            if (!htmlfields.get("dob").equals("")) {
                SimpleDateFormat formatter1 = new SimpleDateFormat("MM/dd/yyyy");
                java.util.Date d = (java.util.Date) formatter1.parse(htmlfields.get("dob").toString());
                dob = new Date(d.getTime());
            }
            sb.setAddressId(adb.getAddressId());
            if (htmlfields.get("admissionId").toString().length() != 0) {
                sb.setAdmissionId(Integer.parseInt(htmlfields.get("admissionId").toString()));
            }
            sb.setStudentName(htmlfields.get("stuName").toString());
            sb.setGender(htmlfields.get("gender").toString());
            if (htmlfields.get("category").toString().length() != 0) {
                sb.setCategoryId(Integer.parseInt(htmlfields.get("category").toString()));
            }
            sb.setEntryEmail(session.getAttribute("uid").toString());
            if (htmlfields.get("studid").toString().length() != 0) {
                sb.setStudentId(Integer.parseInt(htmlfields.get("studid").toString()));
            }

            if (stuChk != 0) {
                i = Student.Query.edit(sb);
            } else {
                i = Student.Query.add(sb);
                if (i != 0) {
                    UserBean ub = new UserBean();
                    ub.setDob(dob);
                    ub.setEmail(null);
                    ub.setEmployeeName(htmlfields.get("stuName").toString());
                    ub.setPassword(100000 + Math.round(Math.random() * 99999) + "");
                    ub.setUserStatus(0);
                    ub.setUserType("Student");
                    ub.setEntryEmail(session.getAttribute("uid").toString());
                    int k = User.Query.addStu(ub, i);
                    if (k != 0) {
                        session.setAttribute("status", "Success");
                        session.setAttribute("msg", "Student Details Added Successfully.");
                        response.sendRedirect("/RIT/Services/Admission/Admission.jsp");
                    } else {
                        session.setAttribute("status", "Fail");
                        session.setAttribute("msg", "Student Details not Added");
                        response.sendRedirect("/RIT/Services/Admission/Admission.jsp");
                    }
                }
            }

            if (i != 0) {
                session.setAttribute("status", "Success");
                session.setAttribute("msg", "Student Details Edited Successfully.");
                response.sendRedirect("/RIT/Services/Admission/Admission.jsp");
            } else {
                out.println("else");
                session.setAttribute("status", "Fail");
                session.setAttribute("msg", "Student Details not Edited.");
                response.sendRedirect("/RIT/Services/Admission/Admission.jsp");
            }

        } catch (IOException e) {
            out.println(e);
            session.setAttribute("status", "Fail");
            session.setAttribute("msg", "Student Details not Edited.(e)");
            response.sendRedirect("/RIT/Services/Admission/Admission.jsp");
        } catch (NumberFormatException e) {
            out.println(e);
            session.setAttribute("status", "Fail");
            session.setAttribute("msg", "Student Details not Edited.(e)");
            response.sendRedirect("/RIT/Services/Admission/Admission.jsp");
        } catch (SQLException e) {
            out.println(e);
            session.setAttribute("status", "Fail");
            session.setAttribute("msg", "Student Details not Edited.(e)");
            response.sendRedirect("/RIT/Services/Admission/Admission.jsp");
        } catch (ParseException e) {
            out.println(e);
            session.setAttribute("status", "Fail");
            session.setAttribute("msg", "Student Details not Edited.(e)");
            response.sendRedirect("/RIT/Services/Admission/Admission.jsp");
        } finally {
            out.close();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            processRequest(request, response);
        } catch (ParseException ex) {
            Logger.getLogger(EditStudent.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /**
     * Handles the HTTP <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            processRequest(request, response);
        } catch (ParseException ex) {
            Logger.getLogger(EditStudent.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
